package co.za.itweb.brainstormlite;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import co.za.itweb.brainstormlite.R;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CitiesActivity extends Activity {
    // Scrolling flag
    private boolean scrolling = false;
    String[] categoryArray;
    String[] companyArray;
    String cities[][];
    ListView lv2;
    private final Object mLock = new Object();
    private CompanyAdapter c_adapter;
	static String[] newar2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.cities_layout);
        
        LinearLayout layout = (LinearLayout) findViewById(R.id.cell6);
        int colors[] =  {Color.parseColor("#FF1f292f"),Color.parseColor("#FF1f292f")};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
		layout.setBackgroundDrawable(grad);
		
		TextView titletext=(TextView) findViewById(R.id.title);
	     titletext.setText("CIO Directory search");
	     
	     ImageButton info=(ImageButton) findViewById(R.id.cell6).findViewById(R.id.info);
		 ImageButton back=(ImageButton) findViewById(R.id.cell6).findViewById(R.id.back);
	    
	     
	     back.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent1 = new Intent(CitiesActivity.this, CioActivity.class);
					intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent1);
					finish();
				}
			});
	     
	     
	     info.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
					startActivity(intent);
					
		
				}
			});
	     
	    
		
        String[] category=new String[CioActivity.CList.get(0)._itemlist.size()];
        for(int x=0;x< CioActivity.CList.get(0)._itemlist.size();x++){
        	
        	category[x]=CioActivity.CList.get(0)._itemlist.get(x).getCategory();
        }
        Arrays.sort(category);
        List<String> list = Arrays.asList(category);
        Set<String> set = new HashSet<String>(list);
        String[] categoryArray = new String[set.size()];
        categoryArray=set.toArray(categoryArray);  
        
        final WheelView country = (WheelView) findViewById(R.id.country);
        country.setVisibleItems(8);
        country.setViewAdapter(new CountryAdapter(this));
      
        	String[]companies=new String[CioActivity.CList.get(0)._itemlist.size()];
        	 for(int f=0;f<CioActivity.CList.get(0)._itemlist.size();f++){
        		 companies[f]=CioActivity.CList.get(0)._itemlist.get(f).getCompany();
        	 }
        	
        	 List<String> l = Arrays.asList(companies);
             Set<String> s = new HashSet<String>(list);
             companyArray = new String[s.size()];
             companyArray=s.toArray(companyArray); 
           
        country.addChangingListener(new OnWheelChangedListener() {
                        public void onChanged(WheelView wheel, int oldValue, int newValue) {
                            if (!scrolling) {
                               // updateCities(city, cities, newValue);
                            	updateList(newValue);
                            }
                        }
                });
        
        country.addScrollingListener( new OnWheelScrollListener() {
            public void onScrollingStarted(WheelView wheel) {
                scrolling = true;
            }
            public void onScrollingFinished(WheelView wheel) {
                scrolling = false;
               // updateCities(city, cities, country.getCurrentItem());
                updateList(country.getCurrentItem());
            }
        });

        country.setCurrentItem(0);
        
       
      
        c_adapter = new CompanyAdapter(this,CioActivity.ar);
        lv2 = (ListView) findViewById(R.id.ListView02);
        lv2.setTextFilterEnabled(true);
        updateList(0);
        lv2.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				
				Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
				intent.putExtra("id2", position);
				
				startActivity(intent);
			}
		});
        
    }
    
    /**
     * Updates the city wheel
     */
    private void updateCities(WheelView city, String cities[][], int index) {
        ArrayWheelAdapter<String> adapter =
            new ArrayWheelAdapter<String>(this, cities[index]);
        adapter.setTextSize(11);
        city.setViewAdapter(adapter);
      
        city.setCurrentItem(cities[index].length);        
    }
    
    private void updateList( int index) {
      
        String[] newar=new String[CioActivity.CList.get(0)._itemlist.size()];
       
        for(int y=0;y<CioActivity.CList.get(0)._itemlist.size();y++){
        	if(CioActivity.CList.get(0)._itemlist.get(y).getCategory().equals(companyArray[index]) && CioActivity.CList.get(0)._itemlist.get(y).getCategory()!=null){
        		System.out.println("ARRAY companije "+companyArray[index]);
        		System.out.println("get company "+CioActivity.CList.get(0)._itemlist.get(y).getCategory());
        		System.out.println("IME "+CioActivity.CList.get(0)._itemlist.get(y).getContactName());
        		if(CioActivity.CList.get(0)._itemlist.get(y).getContactName().length()>5){
        			
        			newar[y]=CioActivity.CList.get(0)._itemlist.get(y).getContactName();
        		}
        	}
        }
        List<String> list = new ArrayList<String>();

        for(String s : newar) {
           if(s != null && s.length() > 5) {
              list.add(s);
           }
        }

         newar2 = list.toArray(new String[list.size()]);
        System.out.println(Arrays.toString(newar2));
        this.c_adapter = new CompanyAdapter(this,newar2);
        lv2.setAdapter(c_adapter);
        c_adapter.notifyDataSetChanged();
             
    }
    
   
    public class CountryAdapter extends AbstractWheelTextAdapter {
       
        private String countries[];
         
      
        protected CountryAdapter(Context context) {
            super(context, R.layout.country_layout, NO_RESOURCE);
            String[] category=new String[CioActivity.CList.get(0)._itemlist.size()];
            for(int x=0;x< CioActivity.CList.get(0)._itemlist.size();x++){
            	
            	category[x]=CioActivity.CList.get(0)._itemlist.get(x).getCategory();
            }
            Arrays.sort(category);
            List<String> list = Arrays.asList(category);
            Set<String> set = new HashSet<String>(list);
            String[] categoryArray = new String[set.size()];
            categoryArray=set.toArray(categoryArray);
            this.countries=categoryArray;
            
            setItemTextResource(R.id.country_name);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            ImageView img = (ImageView) view.findViewById(R.id.flag);
            img.setImageResource(R.drawable.right_arrow);
            return view;
        }
        
        @Override
        public int getItemsCount() {
            return countries.length;
        }
        
        @Override
        protected CharSequence getItemText(int index) {
            return countries[index];
        }
    }
    
    
    private class CompanyAdapter extends BaseAdapter {
    	private Filter filter;
        private String[] items;
        public  ImageLoader imageLoader; 
        public CompanyAdapter(Context context, String[] items) {
               
                this.items = items;
                imageLoader=new ImageLoader(context);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.contact_row, null);
                }
               
               
                	TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        ImageView iv=(ImageView) v.findViewById(R.id.icon);
                      
                        if (tt != null) {
                              tt.setText(items[position]); 
                        }
                        if (iv != null) {
                        	for(int t=0;t<CioActivity.CList.get(0)._itemlist.size();t++){
                        		if(items[position].equals(CioActivity.CList.get(0)._itemlist.get(t).getContactName())){
                        			imageLoader.DisplayImage(CioActivity.CList.get(0)._itemlist.get(t).getContactIcon(), iv);
                        			
       	                        	 bt.setText("Company: "+CioActivity.CList.get(0)._itemlist.get(t).getCompany()+"\n"+ "Category: "+CioActivity.CList.get(0)._itemlist.get(t).getCategory()); 
       	                        
                        		}
                        	}
                        	 
                        }
                       
                return v;
        }
        
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return items.length;
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items[position];
		}
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		
			
}
    
    
   
    
    
}